﻿Imports ACompany.OrderProcessing.Model
Imports ACompany.OrderProcessing.Services
Imports StructureMap

Public Class ProductListPresenter

    Private _View As IProductListView
    Private _ProductService As IProductService
    Private _OrderService As IOrderService

    Public Sub New(ByVal View As IProductListView)
        Me.New(View, ObjectFactory.GetInstance(Of IOrderService)(), ObjectFactory.GetInstance(Of IProductService)())
    End Sub

    Public Sub New(ByVal View As IProductListView, _
                   ByVal OrderService As IOrderService, _
                   ByVal ProductService As IProductService)
        _View = View
        _ProductService = ProductService
        _OrderService = OrderService
    End Sub

    Public Sub Display()

        clearInfoAndErrorMessages()

        Dim products As List(Of Product)
        products = _ProductService.FindAll

        _View.Products = products

    End Sub

    Public Sub RemoveProductBy(ByVal ProductId As Guid)

        clearInfoAndErrorMessages()

        If _OrderService.FindAllOrdersContainingProductBy(ProductId).Count = 0 Then

            Dim productToRemove As Product
            productToRemove = _ProductService.FindBy(ProductId)

            If Not productToRemove Is Nothing Then
                _ProductService.Remove(productToRemove)
                Display()
            Else
                ' Display error
                _View.ErrorMessage(String.Format("Could not find a product with the Id {0}", ProductId))
            End If

        Else
            ' Display error
            _View.ErrorMessage("This product is associated with some orders and so it cannot be removed")
        End If

    End Sub

    Private Sub clearInfoAndErrorMessages()
        _View.ErrorMessage(String.Empty)
        _View.InfoMessage(String.Empty)
    End Sub


End Class

